#! C:\Perl\bin\perl.exe

# Copyright (c) 2010, College Center for Library Automation

# See the included Copyright.txt file for full license

#
# contact ebrary get stats for each and college requested. login once per college and then request each month seperately.
# additional comment

use strict;
use warnings;

use LWP::UserAgent;
use HTTP::Request;
use HTTP::Request::Common;
use Date::Calc qw(Add_Delta_YM Today Delta_Days);
use Text::CSV;

use avsCommon;

dbsetup();

my ($content, $response, $request, $url);
my ($runyear, $runmonth, $runday, @rundate);
my $ua = new LWP::UserAgent(keep_alive=>1);
$ua->cookie_jar( {} );

do {
	doLogin ();

  @rundate = @begdate;
  
	while (Delta_Days(@rundate, @enddate) > 0) {
		getStats ();
		@rundate = Add_Delta_YM(@rundate, 0, 1);	# advance the month
	};

	doLogout ();
} while $sthlogin->fetch;

dbshutdown();

exit;

sub doLogin {

	#login college
	$url = 'https://partners.ebrary.com/ReportLogin';
	
	$request = HTTP::Request->new(POST => $url);
	$request->content_type('application/x-www-form-urlencoded');
	$request->content("type=Library&userName=$username&password=$password");
	$response = $ua->request($request);
	
	if (!$response->is_success && substr($response->status_line,0,3) ne '302') {
		die "#error:$0: GET login $url :" . $response->status_line;
	};
	
	# this may not be needed, although it sets a jsessionid cookie
	$url = 'https://partners.ebrary.com/LibHome?type=';
	$response = $ua->request(GET $url);

	# this sets a several cookies
	$url = 'https://partners.ebrary.com/reportsRedirector.jsp';
	$response = $ua->request(GET $url);
	$content = $response->decoded_content;

}

# run once for each month in optional range. typically beg and end month the same.
sub getStats {

	# ask for report
	($runyear, $runmonth, $runday) = @rundate;
	$url = 'http://reports.ebrary.com/ibi_apps/WFServlet';

	$request = HTTP::Request->new(POST => $url);
	$request->content_type('application/x-www-form-urlencoded');
	$request->content('IBIC_server=EDASERVE&IBIAPP_app=ebraryexternal&IBIF_ex=0010_1_counter_report&WFFMT=COMT&MONTH=CUSTOM&FROM_MONTH='
		.sprintf('%02d%04d', $runmonth, $runyear).'&TO_MONTH='.sprintf('%02d%04d', $runmonth, $runyear).'&LAUNCH_RPT=BR6&IBIMR_Random='.rand());

	$response = $ua->request($request);

	if (!$response->is_success) {
		die "#error:$0: POST report $url :" . $response->status_line;
	};

	# the created file location is in some javascript. find it and redirect there to get the data
	if (!($response->decoded_content =~ /location.replace\("(?<location>.*?)"\);/mi)) {
		warn "#info: no data found for college $collegeid $runmonth$runyear\n";
		return;
	}

	$url = 'http://reports.ebrary.com' . $+{location};

	$response = $ua->request(GET $url);
	$content = $response->decoded_content;

	# save contents for possible debugging
	savecontent('Ebrary', "$collegeid-$runyear-$runmonth", $content);

	my @contents = split ("\r\n", $content);

	my $datasource = 'All Titles';

	my $csv = Text::CSV->new({binary => 1});
	my $ebooks;
	my $sessions;
	# parse each csv line, start with ~line 1 to 1 before the end
	foreach my $content (@contents[1..$#contents]) {

		# ignore blank lines
		if (! $content) {
			next;
		};

		#parse the line
		if ($csv->parse($content)) {
			my @columns = $csv->fields();

			# data line is either session or searches. save information appropriately
			if ($columns[3] =~/sessions/i) {
				$sessions = $columns[4];
			}
			elsif ($columns[3] =~/searches/i) {
				$ebooks = $columns[4];
			}
			else {
				print "#error: expected 'sessions' or 'searches', found: $columns[3]\n";
			}
		}

		else {
			my $err = $csv->error_input;
			print "#error:$0: csv parse error : $err\n";
		}
	}
	my $period = myperiod($runyear, $runmonth);
	print "$vendorid $collegeid $period $datasource $sessions $ebooks\n";
	$sthstats->execute($vendorid, $collegeid, $datasource, $period, $sessions, $SESSIONS)
		or die '#error: sthstats execute 1 failed';
	$sthstats->execute($vendorid, $collegeid, $datasource, $period, $ebooks, $EBOOKS)
		or die '#error: sthstats execute 2 failed';
}

sub doLogout {
#logout college
	$url = 'https://partners.ebrary.com/ReportLogout';
	$response = $ua->request(GET $url);
}